package com.jrx.anytxn.reporting.job.reportingFile.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.ReportingFileConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class RepaymentPlanFileListener implements JobExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(RepaymentPlanFileListener.class);


    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ReportingFileConfig reportingFileConfig;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        String reportingPath = reportingFileConfig.getReportingFilePath();
        String fileName = reportingFileConfig.getReportingFileName();

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String collectionFileName = ReportingConstant.REPORTING_FILE_TYPE_PAYMENT_PLAN+ "_" + toDay + "_" + fileName + ".txt";

        String filePath = reportingPath + org.getTenantId() + File.separator + toDay + File.separator;

        Path reportingFile = Paths.get(filePath + collectionFileName);
        Path pFile = Paths.get(filePath);

        if (!Files.exists(reportingFile)) {
            //判断文件夹是否存在
            if (!Files.isDirectory(pFile)) {
                //创建文件夹
                try {
                    Files.createDirectories(pFile);
                } catch (IOException e) {
                    logger.error("创建目录失败", e);
                }
            }
        } else {
            // 文件存在，则删除
            try {
                Files.delete(reportingFile);
            } catch (IOException e) {
                logger.error("文件{}删除失败", reportingFile, e);
            }
        }
        //创建文件
        try {
            Files.createFile(reportingFile);
        } catch (IOException e) {
            logger.error("创建文件失败", e);
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }
}
